# -*- coding: utf-8 -*-
# @Author : want_login
# @Time : 2019/11/19 下午3:42

# 用户上传

from qiniu import Auth,put_file,etag,put_data
QINIU_ACCESS_KEY = 'ee7DUIjFVPssTMSPkXDkL7I14ZPkzQ9vUix5LV2j'
QINIU_SECRET_KEY = 'aCpM-Kei5CMhtSnc0KmHMeA72nj06TL5mBzk8O0a'
QINIU_BUCKET_NAME = 'zhanghaha'
IMG_BUCKET_NAME = 'zhanghaha-house-img'
def storage(file_data):
    """
    上传文件
    :param file_data:  要上传的文件
    :return:    返回URL
    """
    # 创建授权对象
    q = Auth(QINIU_ACCESS_KEY, QINIU_SECRET_KEY)

    # 生成一个上传的token
    token = q.upload_token(QINIU_BUCKET_NAME,None,7200)

    ret,info = put_data(token,None,file_data)

    if info.status_code == 200:
        #success
        return ret.get('key')
    else:
        #fault
        raise Exception("上传失败")
    # print(info)
    # print("*"*10)
    # print(ret)
    # assert ret['key']== key
    # assert ret['hash'] == etag(localfile)

def storage_img(file_data):
    """
    上传文件
    :param file_data:  要上传的文件
    :return:    返回URL
    """
    # 创建授权对象
    q = Auth(QINIU_ACCESS_KEY, QINIU_SECRET_KEY)

    # 生成一个上传的token
    token = q.upload_token(IMG_BUCKET_NAME,None,7200)

    ret,info = put_data(token,None,file_data)

    if info.status_code == 200:
        #success
        return ret.get('key')
    else:
        #fault
        raise Exception("上传失败")
if __name__ == '__main__':
    with open("./IMG_0380.jpg",'rb')as f:
        file_data = f.read()
        storage(file_data)


